<?php


namespace app\api\controller;


use app\BaseController;
use think\facade\Db;
use util\JwtUtils;

class Wechat extends BaseController
{
    public function register(){
        $mobile = request()->post('mobile');
        $userInfo=Db::table("staff")->where("mobile",$mobile)->find();
        if(empty($userInfo)){
            parent::sendOutput("手机号码不存在",500);
        }
        $password= request()->post('password');
        if($userInfo["password"]!=md5($password)){
            parent::sendOutput("密码不正确",500);
        }
        if(!empty($userInfo["openid"])){
            parent::sendOutput("该账号已经绑定，请联系管理员",500);
        }
        $openid= request()->post('openid');
        Db::table("staff")->where("id",$userInfo["id"])->update(["openid"=>$openid,"register_time"=>date('Y-m-d H:i:s')]);
        $userInfo["openid"]=$openid;
        $token=JwtUtils::getToken($userInfo);
        parent::sendOutput(["type"=>"login",'accessToken' => $token,"openid"=>$openid]);
    }
    public function getStaffUserId(){
        $code = request()->get('auth_code');
        $appid = "wx1a900d41dd38ffb1";//小程序的唯一标识
        $secret = "4657954ae1e9f46e37cba8f71468bffe";//小程序的AppSecret
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';

        $tmpInfo = file_get_contents( $url);//执行操作

        // $tmpInfo = json_decode(json_encode(simplexml_load_string($tmpInfo, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        $tmpInfo = $this->object_to_array(json_decode($tmpInfo));

        if (!empty($tmpInfo['errmsg'])) {
            parent::sendOutput($tmpInfo['errmsg'],500);
            return json(['code' => '500',"msg"=>$tmpInfo['errmsg']]);
        } else {
            $userInfo=Db::table("staff")->where("openid",$tmpInfo["openid"])->find();
            if(empty($userInfo)){
                parent::sendOutput(["type"=>"register","openid"=>$tmpInfo["openid"]]);
            }else{

                $token=JwtUtils::getToken($userInfo);
                parent::sendOutput(["type"=>"login",'accessToken' => $token,"openid"=>$tmpInfo["openid"]]);
            }
        }
    }
    public function object_to_array($obj){
        $_arr = is_object($obj) ? get_object_vars($obj) :$obj;
        foreach($_arr as $key=>$val){
            if($key !== 'gioouts'){
                $val = (is_array($val) || is_object($val)) ? $this->object_to_array($val):$val;
                $arr[$key] = $val;
            }
        }
        return $arr;
    }
}